﻿using System;
using System.Collections.Generic;
using System.Linq;
using Autofac;
using DapperWrapper;
using ZL.CRM.CommonEntity.AccOpr.Web;
using ZL.Web.Utility;
using ZL.Web.Utility.Cache;
using ZL.Web.Utility.Config;
using ZL.Web.Utility.Snowflake;
using ZL.Web.Utility.SnowflakeService;
using ZLWeb.WebApiEntity.MemberCard;
using ZLWeb.WebApiEntity.WechatCardModel;
using ZLWeb.WebApiEntityBase;
using ZLWeb.WebApiEntityBase.RedisEntity;
using ZLWeb.WebApiInfrastructure.Base;
using ZLWeb.WebApiInfrastructure.Filter;
using ZLWeb.WebApiRepository.Base;
using ZLWeb.WebApiRepository.InterFace;
using ZLWeb.WebApiEntity.EasyUse;
using ZLWeb.WebApiEntityBase.Cache;
using ZilLion.Service.Core.CRMUnities.IOC;
using Microsoft.AspNetCore.Mvc;
using ZilLion.Service.Core.DapperWrapper;
using ZilLion.Service.Core.ModelBase;
using Microsoft.AspNetCore.Authorization;
using ZLWeb.WebApiControllers.Log;
using ZilLion.Service.Core.WechatService.Domain;

namespace ZilLion.Service.Core.WechatService.Controller
{
    /// <summary>
    ///     方便用
    /// </summary>
    [Route("Api/EasyUse")]
    [AllowAnonymous]
    public class EasyUseController : WebApiBase
    {

        //[Route("GetNo")]
        [SplitDB]
        [HttpGet("GetNo")]
        public ZLWeb.WebApiEntity.WechatCardModel.AccInfo GetNo()
        {
            var paymentRepo = ClassFactory.GetInstance<IPaymentRepository>(DBContextparameter, Accidparameter);
            AccInfo info = paymentRepo.GetAccInfoquery();
            //if (info != null)
            //{
            //    var CacheLoader = GloabConfigCacheLoader.CreateGloabConfigCacheLoader();
            //    JltyZklbCacheItem Jitem = CacheLoader.GetJltyZklbCache();
            //    //if (Jitem != null)
            //    //{
            //    //    Jltycrmkyzklbt kyzklbt = Jitem.kyzklbts.FirstOrDefault(tr => tr.kzkhsign == 1);
            //    //    info.acccellno = kyzklbt.zklbqyday;
            //    //}
            //}
            return info;
        }


        [Route("GetAllAccInfo")]
        [HttpGet]
        public WxShowInfo GetAllAccInfo()
        {
            var paymentRepo = ClassFactory.GetInstance<IPaymentRepository>(DBContextparameter, Accidparameter);
            WxShowInfo item = paymentRepo.GetAccWxShowInfo();
            LoadShowInfo(item);
            return item;
        }

        [Route("SimpleRegesiter")]
        [HttpPost]
        public ResponseResultInfo SimpleRegesiter(ZL.CRM.CommonEntity.AccOpr.Web.AccThrOpenYwdetail infoy)
        {
            infoy.oprywwindow = "手机开户客户端";
            infoy.oprsummary = "手机开户客户端";
            var SnowflakeService = ClassFactory.GetInstance<ISnowflakeService>();
            long opraccid = SnowflakeService.GetId(long.Parse(ZLConfig.WorkerId));
            Accid = opraccid;
            var regesiterRepo = ClassFactory.GetInstance<IRegesiterRepository>(new NamedParameter("Accid", opraccid));
            infoy.Ywcore.oprctype = 2;
            LoadCache(infoy.Ywcore);
            var oprpj = Guid.NewGuid().ToString().Substring(0, 5);
            var sd = new dpno();
            infoy.Ywcore.opraccid = opraccid;
            infoy.Ywcore.oprsno = SnowflakeService.GetSno(long.Parse(ZLConfig.WorkerId), "CR");
            sd.pno = Guid.NewGuid().ToString().Substring(0, 5);
            sd.pnopwd = Guid.NewGuid().ToString().Substring(0, 5);
            infoy.Ywcore.oprtime = DateTime.Now;
            infoy.Ywcore.oprbrname = "手机微信开户";
            ResponseResultInfo item = regesiterRepo.SimpleRegesiter(infoy.Ywcore, oprpj);
            if (item.Errormodel == null)
            {
                SqlConnectionLoader accidloader = new SqlConnectionLoader(infoy.Ywcore.opraccid);
                IDbContext DbContext = accidloader.GetDbContext();
                IMultiDbContext MultiDb = DbContext as IMultiDbContext;
                var accidModel = new AccidModel
                {
                    openid = infoy.Ywcore.oprcardno,
                    //wxcardno = infoy.Ywcore.cardgsidsbm + infoy.Ywcore.carddissbm + "0" + infoy.Ywcore.wxcardno,
                    wxcardno = "0" + infoy.Ywcore.wxcardno,
                    cellphone = infoy.Ywcore.oprcellphone,
                    accid = infoy.Ywcore.opraccid,
                    ConstrName = MultiDb.miid + MultiDb.miidtype + MultiDb.mikvname
                };
                StoreAccidModel(accidModel);
                ZLEventLog.CreateZLEventLog(Accid.GetValueOrDefault(), Openid).LogAction(infoy);
            }
            return item;

        }

        private void LoadCache(ZL.CRM.CommonEntity.AccOpr.Web.AccThrOpenYwcore ywcore)
        {
            var CacheLoader = GloabConfigCacheLoader.CreateGloabConfigCacheLoader(new WechatServiceContext());
            JltyZklbCacheItem Jitem = CacheLoader.GetJltyZklbCache();
            if (Jitem != null)
            {
                Jltycrmkyzklbt kyzklbt = Jitem.kyzklbts.FirstOrDefault(tr => tr.kzkhsign == 1);
                ywcore.carddisid = kyzklbt.zklbid;
                ywcore.carddissbm = kyzklbt.zklbsbm;
                ywcore.carddissxrq = DateTime.Now.AddDays(kyzklbt.zklbqyday);
            }
            JltyKzCacheItem Jlitem = CacheLoader.GetJltyKzCache();
            if (Jlitem != null)
            {
                Jltycrmkykzt klbt = Jlitem.kykzts.FirstOrDefault(tr => tr.kzkhsign == 1);
                ywcore.cardgsid = klbt.kzid;
                ywcore.cardgsidsbm = klbt.kzsbm;
            }
        }

        private void LoadShowInfo(WxShowInfo item)
        {
            var CacheLoader = GloabConfigCacheLoader.CreateGloabConfigCacheLoader(new WechatServiceContext());
            JltyZklbCacheItem Jitem = CacheLoader.GetJltyZklbCache();
            if (Jitem != null)
            {
                Jltycrmkyzklbt kyzklbt = Jitem.kyzklbts.FirstOrDefault(tr => tr.zklbid == item.accdisid);
                item.wxcardno = kyzklbt.zklbsbm + item.wxcardno;
            }
            JltyKzCacheItem Jlitem = CacheLoader.GetJltyKzCache();
            if (Jlitem != null)
            {
                Jltycrmkykzt klbt = Jlitem.kykzts.FirstOrDefault(tr => tr.kzid == item.acccgsid);
                item.wxcardno = klbt.kzsbm + item.wxcardno;
            }
        }

        private void LoadCache(ZL.CRM.CommonEntity.AccOpr.Web.AccBindingCardYwdetail ywcore)
        {
            var CacheLoader = GloabConfigCacheLoader.CreateGloabConfigCacheLoader(new WechatServiceContext());
            JltyZklbCacheItem Jitem = CacheLoader.GetJltyZklbCache();
            if (Jitem != null)
            {
                Jltycrmkyzklbt kyzklbt = Jitem.kyzklbts.FirstOrDefault(tr => tr.zklbsbm == ywcore.Ywcore.zklbsbm);
                ywcore.Ywcore.zklbid = kyzklbt.zklbid;
            }
            JltyKzCacheItem Jlitem = CacheLoader.GetJltyKzCache();
            if (Jlitem != null)
            {
                Jltycrmkykzt klbt = Jlitem.kykzts.FirstOrDefault(tr => tr.kzsbm == ywcore.Ywcore.kzsbm);
                ywcore.Ywcore.kzid = klbt.kzid;
            }
        }

        private void StoreAccidModel(AccidModel accidModel)
        {
            Dictionary<string, AccidModel> TMP = new Dictionary<string, AccidModel>();
            TMP.Add("2" + accidModel.openid, accidModel);
            TMP.Add("4" + accidModel.cellphone, accidModel);
            TMP.Add("6" + accidModel.wxcardno, accidModel);
            SERedisHelper.BatchSet<AccidModel>(TMP, null);
        }

        [Route("BindOldCardv2")]
        [HttpPost]
        public ZL.CRM.CommonEntity.AccOpr.Web.AccBindingCardMemberno BindOldCardv2(ZL.CRM.CommonEntity.AccOpr.Web.AccBindingCardYwdetail info)
        {
            LoadCache(info);
            info.Ywcore.oprtime = DateTime.Now;
            info.cdesc = "微信绑定实体卡";
            ISnowflakeService SnowflakeService = ClassFactory.GetInstance<ISnowflakeService>();
            info.Ywcore.oprsno = SnowflakeService.GetSno(long.Parse(ZLConfig.WorkerId), "CZ");
            var repo = ClassFactory.GetInstance<IBindOldCardRepository>(Accidparameter);
            var item = repo.BindOldCard(info);
            if (item.Errormodel == null)
            {
                info.Memberno = new ZL.CRM.CommonEntity.AccOpr.Web.AccBindingCardMemberno();
                info.Memberno.memberno = item.memberno;
                AccidModel sm = SERedisHelper.Get<AccidModel>("6" + item.memberno);
                if (sm != null)
                {
                    sm.scardno = info.Ywcore.cardno;
                    SERedisHelper.Set<AccidModel>("1" + info.Ywcore.cardno, sm, null);
                    SERedisHelper.KeyDelete("6" + item.memberno);
                }
            }
            ZLEventLog.CreateZLEventLog(Accid.GetValueOrDefault(), Openid).LogAction(info);
            return item;
        }


        [Route("GetBalanceChanges")]
        [HttpGet]
        public AccOprInfoResponse GetBalanceChanges()
        {
            var repository = ClassFactory.GetInstance<IAccOprInfoRepository>(DBContextparameter, Accidparameter);
            var items = repository.GetBalanceChanges();
            var Zlfixedlist = GloabConfigCacheLoader.CreateGloabConfigCacheLoader(new WechatServiceContext()).GetZlfixedlistCacheItem();
            foreach (var item in items)
            {
                var Zlfixed = Zlfixedlist.Zlfixedlists.FirstOrDefault(tr => tr.Flid == item.oprtype && tr.Flsign == "zczlx");
                item.oprtypesm = Zlfixed.Flname;
            }
            return new AccOprInfoResponse() { AccOprInfos = items };
        }

        [Route("CheckBindingCardNo")]
        [HttpGet]
        public AccEntitycard CheckBindingCardNo()
        {
            var paymentRepository = ClassFactory.GetInstance<IPaymentRepository>(DBContextparameter, Accidparameter);
            return paymentRepository.CheckBindingCardNo();
        }

        [Route("CartAdd")]
        [HttpPost]
        public ResponseResultInfo CartAdd(ZL.CRM.CommonEntity.AccOpr.Web.AccWxCardAddDetail CardAddDetail)
        {

            ISnowflakeService SnowflakeService = ClassFactory.GetInstance<ISnowflakeService>();
            CardAddDetail.Ywcore.oprsno = SnowflakeService.GetSno(long.Parse(ZLConfig.WorkerId), "ZL");
            var paymentRepository = ClassFactory.GetInstance<IPaymentRepository>(Accidparameter);
            var item = paymentRepository.CartAdd(CardAddDetail);
            if (item.Errormodel == null)
            {
                SqlConnectionLoader accidloader = new SqlConnectionLoader(Accid.GetValueOrDefault());
                IDbContext DbContext = accidloader.GetDbContext();
                IMultiDbContext MultiDb = DbContext as IMultiDbContext;
                var accidModel = new AccidModel
                {
                    openid = CardAddDetail.Ywcore.newcardno,
                    cellphone = CardAddDetail.Ywcore.cellno,
                    accid = Accid.GetValueOrDefault(),
                    ConstrName = MultiDb.miid + MultiDb.miidtype + MultiDb.mikvname
                };
                SERedisHelper.Set<AccidModel>("2" + accidModel.openid, accidModel, null);
                AccidModel Aitem = SERedisHelper.Get<AccidModel>("4" + accidModel.cellphone);
                Aitem.Accids = new List<AccidModel>();
                Aitem.Accids.Add(accidModel);
                SERedisHelper.KeyDelete("4" + accidModel.cellphone);
                SERedisHelper.Set<AccidModel>("4" + accidModel.cellphone, Aitem, null);
                ZLEventLog.CreateZLEventLog(Accid.GetValueOrDefault(), Openid).LogAction(CardAddDetail);
            }
            return item;
        }

        [Route("ChargeNewSave")]
        [HttpPost]
        //[SplitDB]
        public Thrpaylog ChargeNewSave(Thrpaylog log)
        {
            var cache = GloabConfigCacheLoader.CreateGloabConfigCacheLoader(new WechatServiceContext()).GetGxcspzCacheItem();
            if (cache != null)
            {
                var pzhkeyitem = cache.gxcses.FirstOrDefault(tr => tr.shxkey == "ZxCzCwhsjgid");
                var hxjgmcitem = cache.gxcses.FirstOrDefault(tr => tr.shxkey == "ZxCzCwhsjgmc");
                log.xlog.tlglywxx = log.xlog.tlglywxx + "|" + pzhkeyitem.shxvalue + "|" + hxjgmcitem.shxvalue;
            }
            var chargeRepo = ClassFactory.GetInstance<IChargeRepository>(DbContextparameter);
            var plog = chargeRepo.ChargeNewSave(log, log.payway);
            ZLEventLog.CreateZLEventLog(Accid.GetValueOrDefault(), Openid).LogAction(plog.xlog);
            return plog;
        }

        [Route("GetPayLog")]
        [HttpPost]
        public Ywxx GetPayLog(QueryParam param)
        {
            var chargeRepo = ClassFactory.GetInstance<IChargeRepository>(DbContextparameter);
            return chargeRepo.GetPayLog(param.tllsh, param.tlfjzt);
        }

        [Route("ChargeResultQuery")]
        [HttpPost]
        public Result ChargeResultQuery(QueryParam param)
        {
            var chargeRepo = ClassFactory.GetInstance<IChargeRepository>(DbContextparameter);
            return chargeRepo.ChargeResultQuery(param.payway, param.tllsh, param.tlfjzt);
        }

        [Route("ChargeAccure")]
        [HttpPost]
        public ResponseResultInfo ChargeAccure(ZL.CRM.CommonEntity.AccOpr.Web.AccThrCzYwdetail log)
        {
            var chargeRepo = ClassFactory.GetInstance<IChargeRepository>(DBContextparameter, Accidparameter);
            var item = chargeRepo.ChargeAccure(log, log.tllshfjz, 1);
            if (item != null) log.Ywcore = item;
            ZLEventLog.CreateZLEventLog(Accid.GetValueOrDefault(), Openid).LogAction(log);
            return new ResponseResultInfo();
        }

        [Route("GetAccWxmprel")]
        [HttpGet]
        public RelResult GetAccWxmprel(string openappid, string code, string cardid)
        {
            var repository = ClassFactory.GetInstance<IPaymentRepository>(DBContextparameter, Accidparameter);
            return repository.GetAccWxmprel(openappid, code, cardid);
        }


    }
}